﻿#pragma execution_character_set("utf-8")
#include "stdafx.h"
#include "mainwindow.h"
#include "delegate.h"
#include "frmdbpage.h"
#include "contact.h"
#include "fuzzySearch.h"

enum E_Cols
{
    E_Cols_Path = 0,
    E_Cols_Name,
    E_Cols_like,
    E_Cols_Collection,
    E_Cols_times
};

void MainWindow::setView(QTableView* view)
{
    view->setSortingEnabled(true);
    view->setSelectionBehavior(QAbstractItemView::SelectRows);
    view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    view->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    view->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    
    view->setItemDelegateForColumn(E_Cols_Path, new ReadOnlyDelegate(this));
    view->setItemDelegateForColumn(E_Cols_Name, new ReadOnlyDelegate(this));
    view->setItemDelegateForColumn(E_Cols_like, new SpinBoxDelegate(this));
    view->setItemDelegateForColumn(E_Cols_Collection, new ComboBoxDelegate(this));
    view->setItemDelegateForColumn(E_Cols_times, new ReadOnlyDelegate(this));
	connect(view, &QTableView::doubleClicked, this, &MainWindow::onDoubleClicked);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    resize(1000, 600);

    QMenuBar *bar = menuBar();
    this->setMenuBar(bar);

    QMenu *fileMenu = bar->addMenu("File");
    QAction *openAction = fileMenu->addAction("Open");
    connect(openAction, &QAction::triggered, this, &MainWindow::onOpen);

	tabWidget = new QTabWidget(this);
	connect(tabWidget, &QTabWidget::currentChanged, this, &MainWindow::onTabChanged);
	setCentralWidget(tabWidget);

	// All
	{
		auto model = new QSqlTableModel(this);
		model->setTable("video");
		model->setEditStrategy(QSqlTableModel::OnFieldChange);
		model->select();

		auto view = new QTableView(this);
		view->setModel(model);
		setView(view);
		tabWidget->addTab(view, "All");
	}

	// DB Page
	{
		frmDbPage* page = new frmDbPage(this);
		connect(page->getView(), &QTableView::doubleClicked, this, &MainWindow::onDoubleClicked);
		tabWidget->addTab(page, "DB Page");
	}

    // 模糊查找1
    {
        auto findPage = new Contact(this);
        connect(findPage->_view, &QTableView::doubleClicked, this, &MainWindow::onDoubleClicked);
        setView(findPage->_view);
        tabWidget->addTab(findPage, "模糊查找1");
    }

	// 模糊查找2
	{
		auto findPage = new FuzzySearch(this);
		connect(findPage->_view, &QTableView::doubleClicked, this, &MainWindow::onDoubleClicked);
		setView(findPage->_view);
		tabWidget->addTab(findPage, "模糊查找2");
	}

	// 未播放
	{
		auto model = new QSqlTableModel(this);
		model->setTable("video");
		model->setEditStrategy(QSqlTableModel::OnFieldChange);
        model->setFilter("播放次数 = 0");
		model->select();

		auto view = new QTableView(this);
		//view->setColumnHidden(E_Cols_Path, false);
		//view->setColumnWidth(E_Cols_Path, 0);
		view->setModel(model);
		setView(view);
		tabWidget->addTab(view, "未播放");
	}

	// 播放
	{
		auto model = new QSqlTableModel(this);
		model->setTable("video");
		model->setEditStrategy(QSqlTableModel::OnFieldChange);
        model->setFilter("播放次数 > 0");
		model->select();

		auto view = new QTableView(this);
		view->setColumnHidden(E_Cols_Path, false);
		view->setModel(model);
		setView(view);
		tabWidget->addTab(view, "播放");
	}

	// 喜欢
	{
		auto model = new QSqlTableModel(this);
		model->setTable("video");
		model->setEditStrategy(QSqlTableModel::OnFieldChange);
        model->setFilter("评分 > 0");
		model->select();

		auto view = new QTableView(this);
		view->setColumnHidden(E_Cols_Path, false);
		view->setModel(model);
		setView(view);
		tabWidget->addTab(view, "喜欢");
	}  
}

MainWindow::~MainWindow()
{
}

void MainWindow::onOpen()
{
    QString path = QFileDialog::getExistingDirectory();
    if (path.isEmpty())
    {
        return;
    }

	QFileInfoList paths;
    bool result = searchVideo(path, paths);
    if (result)
    {
        for (auto& path : paths)
        {
            if (!addVideo(path))
            {
                result = false;
                break;
            }
        }
    }

    if (result)
    {
        QMessageBox::information(
                    this,
                    tr("Information"),
                    tr("Open successed!\n")
                    );
    }
    else
    {
        QMessageBox::warning(
                    this,
                    tr("Warning"),
                    tr("Open fail!\n")
                    );
    }
}

void MainWindow::onDoubleClicked(const QModelIndex& index)
{
    int column = index.column();
    if (column == E_Cols_Path ||
		column == E_Cols_Name
		)
    {
		auto view = qobject_cast<QTableView*>(sender());
		if (view)
		{
			auto model = view->model();
			if (model)
			{
				QString text = model->index(index.row(), E_Cols_Path).data().toString();
                qDebug() << text << endl;

                bool result = false;

#if _MSC_VER
				HINSTANCE hHandle = ::ShellExecuteA(NULL, "open", text.toLocal8Bit(), NULL, NULL, SW_SHOWNORMAL);
				if (hHandle)
                {
                    result = true;
				}
#else
                result = playVideo(text);
#endif
//                if(result)
//                {
//                    int times = model->index(index.row(), E_Cols_times).data().toInt();
//                    model->setData(model->index(index.row(), E_Cols_times), ++times);
//                    model->submit();

//                    auto tableModle = qobject_cast<QSqlTableModel*>(model);
//                    if (tableModle)
//                    {
//                        tableModle->select();
//                    }
//                }
			}
		}
    }
}

void MainWindow::onTabChanged(int index)
{
	auto view = qobject_cast<QTableView*>(tabWidget->widget(index));
	if (view)
	{
		auto tableModle = qobject_cast<QSqlTableModel*>(view->model());
		if (tableModle)
		{
			tableModle->select();
		}
    }
}

bool MainWindow::playVideo(const QString &videoPath)
{
    QUrl videoUrl(QString("file:///%1").arg(videoPath));
    if (QDesktopServices::openUrl(videoUrl))
    {
        qDebug() << "Video player started successfully.";
        return true;
    }
    else
    {
        qDebug() << "Failed to start video player.";
        return false;
    }
}

bool MainWindow::searchVideo(const QString &rootPath, QFileInfoList& paths)
{
    QDir dir(rootPath);
    if (!dir.exists())
    {
        return false;
    }

    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::DirsFirst);

    QFileInfoList list = dir.entryInfoList();
    if(list.size() < 1)
    {
        return false;
    }

    for (const QFileInfo& fileInfo: list)
    {
        if(fileInfo.isDir())
        {
            searchVideo(fileInfo.filePath(), paths);
        }
        else
        {
            QString suffix = fileInfo.suffix();
            if (suffix == QString("mp4"))
            {
                paths.append(fileInfo);
            }
        }
    }

    return true;
}

bool MainWindow::addVideo(const QFileInfo &file)
{
	QSqlDatabase db = QSqlDatabase::database("video.db");
	QSqlQuery query(db);

	query.exec(QString("insert into video values('%1', '%2')")
		.arg(file.filePath())
		.arg(file.baseName())
		);

    return true;
}
